/*
* 为什么叫ChooserTree
* 因为我觉得从前端角度来看，这个东西就是一个树
* 但是李娜不同意用树，非要表格嵌套表格
* 所以这个东西产生了
* */
import React, { Component, PropTypes } from 'react';
import { messages } from "share/common";
import { Input, Icon } from "antd";
import SelectorTree from "components/chooser-tree/selector-tree";

class ChooserTree extends Component {

  state = {
    modalShow: false,
    inputValue: '',
    value: []
  };

  componentWillReceiveProps = nextProps => {
    this.handleValue(nextProps.value, false);
  };

  handleFocus = () => {
    this.refs.chooserBlur.focus();
    this.setState({ modalShow: true });
  };

  handleValue = (value, isNeedChange = true) => {
    const { labelKey } = this.props;
    let res = Array.isArray(value) ? (value.length > 3 ? `已选择${value.length}条数据` : this.getValue(value)) : value[labelKey];
    this.setState({ inputValue: res, value, modalShow: false }, () => {
      isNeedChange && this.onChange();
    });
  };

  onChange = () => {
    const { value } = this.state, { onChange } = this.props;
    if(onChange){
      onChange(value);
    }
  };

  getValue = value => {
    const { labelKey } = this.props;
    let res = [];
    value.map(item => {
      res.push(item[labelKey])
    });
    return res.join(',')
  };

  clear = () => {
    this.handleValue([]);
  };

  handleCancel = () => {
    this.setState({ modalShow: false });
  };

  render(){
    const { modalShow, inputValue, value } = this.state;
    const { allowClear, title, tableProps, searchProps, secondTableProps, single, labelKey } = this.props;
    return (
      <div>
        <Input
          onFocus={this.handleFocus}
          placeholder={messages('common.select')/*请选择*/}
          suffix={allowClear ? <Icon type="close-circle" onClick={this.clear}/> : null}
          value={inputValue}
        />
        <SelectorTree
          title={title}
          visible={modalShow}
          onOk={this.handleValue}
          onCancel={this.handleCancel}
          single={single}
          selectedData={value}
          tableProps={tableProps}
          searchProps={searchProps}
          secondTableProps={secondTableProps}
          labelKey={labelKey}
        />
        <div>
          <input
            ref="chooserBlur"
            style={{ opacity: 0, position: 'fixed', width: 0, height: 0, zIndex: -1 }}
          />
        </div>
      </div>
    )
  }

  static propTypes = {
    allowClear: PropTypes.bool,
    title: PropTypes.string.isRequired,
    tableProps: PropTypes.any, // 父表格属性 {url://获取数据的url, props: { columns ...}}
    searchProps: PropTypes.any, //searchForm, eventHandle等
    secondTableProps: PropTypes.any, // 相当于树的子节点属性（这里是表格嵌套中表格的属性），可以不填
    single: PropTypes.bool,
    value: PropTypes.oneOfType([PropTypes.array, PropTypes.object]),
    labelKey: PropTypes.string,
    onChange: PropTypes.func
  };

  static defaultProps = {
    allowClear: false,
    single: false,
    value: [],
    secondTableProps: null
  };
}

export default ChooserTree;
